export const updateWordStatus = async (word, messageHandler) => {
  try {
    // Check if electronAPI is available
    if (typeof window.electronAPI !== 'undefined' && window.electronAPI.updateKnownStatus) {
      const newStatus = word.ok === 'YES' ? 'NO' : 'YES';
      const response = await window.electronAPI.updateKnownStatus({
        word: word.word,
        status: newStatus,
      });

      if (response.success) {
        word.ok = newStatus;
        if (messageHandler && messageHandler.success) {
          messageHandler.success(`单词状态已更新为: ${newStatus === 'YES' ? '已掌握' : '未掌握'}`);
        }
      } else {
        throw new Error(response.error || 'Failed to update word status');
      }
    } else {
      console.warn('Electron API not available, running in browser development mode');
      const newStatus = word.ok === 'YES' ? 'NO' : 'YES';
      word.ok = newStatus;
      if (messageHandler && messageHandler.success) {
        messageHandler.success(`单词状态已更新为: ${newStatus === 'YES' ? '已掌握' : '未掌握'}`);
      }
    }
    
    return { success: true };
  } catch (err) {
    console.error('Error updating word status:', err);
    if (messageHandler && messageHandler.error) {
      messageHandler.error('更新单词状态失败: ' + err.message);
    }
    return { success: false, error: err.message };
  }
};

export const processWordData = (word) => ({
  id: word.id,
  word: word.word,
  trans: word.trans,
  ielst: word.ielst,
  ok: word.ok,
  phonetic: word.phonetic,
  pronounce: word.pronounce,
  uk_speech: word.uk_speech,
  us_speech: word.us_speech,
});

export const filterWords = (words, filterType) => {
  switch (filterType) {
    case 'ielts':
      return words.filter(word => word.ielst === 'YES');
    case 'known':
      return words.filter(word => word.ok === 'YES');
    case 'unknown':
      return words.filter(word => word.ok === 'NO');
    default:
      return words;
  }
};